from django.contrib.auth.models import User, Group, Permission
from rest_framework import serializers
from core.serializers import MessageResponseSerializer

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    
    class Meta:
        model = User
        fields = '__all__'
        read_only_fields = ('id',)
    
    def create(self, validated_data):
        password = validated_data.pop('password')
        user = User.objects.create(**validated_data)
        user.set_password(password)
        user.save()
        return user
    
    def update(self, instance, validated_data):
        if 'password' in validated_data:
            password = validated_data.pop('password')
            instance.set_password(password)
        return super().update(instance, validated_data)

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name', 'permissions')

class PermissionSerializer(serializers.ModelSerializer):
    """
    权限序列化器
    """
    app_label = serializers.CharField(source='content_type.app_label', read_only=True)
    model = serializers.CharField(source='content_type.model', read_only=True)
    
    class Meta:
        model = Permission
        fields = ('id', 'name', 'codename', 'app_label', 'model')
        read_only_fields = fields

class UserDetailSerializer(serializers.ModelSerializer):
    """
    用于返回用户详细信息的序列化器
    """
    groups = GroupSerializer(many=True, read_only=True)
    permissions = serializers.SerializerMethodField(help_text='用户所有权限列表')

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name',
                 'is_active', 'is_staff', 'is_superuser', 'groups',
                 'permissions', 'last_login', 'date_joined')
        read_only_fields = fields

    def get_permissions(self, obj) -> list[str]:
        """
        获取用户所有权限（包括组权限）
        
        Returns:
            list[str]: 用户拥有的所有权限列表
        """
        return list(obj.get_all_permissions())

class EmptySerializer(serializers.Serializer):
    """
    空的序列化器，用于不需要请求体的 API
    """
    pass

class ResetPasswordSerializer(serializers.Serializer):
    """
    重置密码序列化器
    """
    new_password = serializers.CharField(write_only=True)
    confirm_password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        if attrs['new_password'] != attrs['confirm_password']:
            raise serializers.ValidationError({'confirm_password': '两次输入的密码不一致'})
        return attrs

class ChangePasswordSerializer(serializers.Serializer):
    """
    修改密码序列化器
    """
    old_password = serializers.CharField(write_only=True, help_text="当前密码")
    new_password = serializers.CharField(write_only=True, help_text="新密码")

    def validate_old_password(self, value):
        user = self.context['request'].user
        if not user.check_password(value):
            raise serializers.ValidationError("当前密码不正确")
        return value

    def validate_new_password(self, value):
        if len(value) < 8:
            raise serializers.ValidationError("密码长度不能小于8位")
        return value

    def save(self, **kwargs):
        user = self.context['request'].user
        user.set_password(self.validated_data['new_password'])
        user.save()
        return user
